package com.rxt.thermopro.ui.fragment

import android.annotation.SuppressLint
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.util.SparseArray
import android.view.View
import android.widget.RadioButton
import androidx.core.app.ShareCompat
import androidx.core.util.set
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager.widget.ViewPager
import com.app.common.base.BaseFragment
import com.rxt.thermopro.R
import com.rxt.thermopro.adapter.TempGraphPageAdapter
import com.rxt.thermopro.app.LocalDataDao
import com.rxt.thermopro.ex.MediaIntentHelper
import com.rxt.thermopro.viewmodel.BleMessageViewModel
import com.rxt.thermopro.viewmodel.TempGraphViewModel
import kotlinx.android.synthetic.main.fragment_temp_graph.*

class TempGraphFragment : BaseFragment<TempGraphViewModel>() {
    override fun layoutId(): Int {
        return R.layout.fragment_temp_graph
    }

    companion object {
        private const val ARG_TEMP_NUM = "tempNumList"
        private const val ARG_POSITION = "currentPosition"
        private const val ARG_DEVICE_TYPE = "deviceType"
        private const val ARG_ADDRESS = "address"

        fun newInstance(tempNumList: ArrayList<String>, position: Int): TempGraphFragment {
            return TempGraphFragment().apply {
                arguments = Bundle().apply {
                    putStringArrayList(ARG_TEMP_NUM, tempNumList)
                    putInt(ARG_POSITION, position)
                }
            }
        }

        fun newInstance(
            tempNumList: ArrayList<String>, position: Int,
            deviceType: Int, address: String
        ): TempGraphFragment {
            return TempGraphFragment().apply {
                arguments = Bundle().apply {
                    putStringArrayList(ARG_TEMP_NUM, tempNumList)
                    putInt(ARG_POSITION, position)
                    putInt(ARG_DEVICE_TYPE, deviceType)
                    putString(ARG_ADDRESS, address)
                }
            }
        }
    }

    private lateinit var mAdapter: TempGraphPageAdapter
    private val fragmentList = SparseArray<Fragment>()
    private var currentPosition = -1
    private var mDeviceType=-1
    private var mAddress=""
    private lateinit var mBleViewModel: BleMessageViewModel
    private lateinit var tempNumList: ArrayList<String>

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        currentPosition = arguments?.getInt(ARG_POSITION, -1) ?: -1
        mDeviceType = arguments?.getInt(ARG_DEVICE_TYPE, -1) ?: -1
        mAddress = arguments?.getString(ARG_ADDRESS, "") ?: ""

        if (mDeviceType==BleMessageViewModel.DEVICE_TYPE_TP960){
            probeView.isVisible=false
        }

        tempNumList = arguments?.getStringArrayList(ARG_TEMP_NUM) ?: arrayListOf()
        mBleViewModel =
            ViewModelProvider(requireActivity()).get(BleMessageViewModel::class.java)
        when (tempNumList.size) {
            1 -> {
                fragmentList[0] = TempGraphPageFragment.newInstance(0,mDeviceType,mAddress)
                page2.isVisible = false
                page3.isVisible = false
                page4.isVisible = false
            }
            2 -> {
                fragmentList[0] = TempGraphPageFragment.newInstance(0,mDeviceType,mAddress)
                fragmentList[1] = TempGraphPageFragment.newInstance(1,mDeviceType,mAddress)
                page3.isVisible = false
                page4.isVisible = false
            }
            3 -> {
                fragmentList[0] = TempGraphPageFragment.newInstance(0,mDeviceType,mAddress)
                fragmentList[1] = TempGraphPageFragment.newInstance(1,mDeviceType,mAddress)
                fragmentList[2] = TempGraphPageFragment.newInstance(2,mDeviceType,mAddress)
                page4.isVisible = false
            }
            4 -> {
                fragmentList[0] = TempGraphPageFragment.newInstance(0,mDeviceType,mAddress)
                fragmentList[1] = TempGraphPageFragment.newInstance(1,mDeviceType,mAddress)
                fragmentList[2] = TempGraphPageFragment.newInstance(2,mDeviceType,mAddress)
                fragmentList[3] = TempGraphPageFragment.newInstance(3,mDeviceType,mAddress)
            }
        }

        mAdapter = TempGraphPageAdapter(childFragmentManager, fragmentList)
        viewPage.adapter = mAdapter
        viewPage.offscreenPageLimit = 3

        initListener()

        mBleViewModel.notifyMsgData.observeInFragment(this, Observer {item->
            val it=item.values.last()
            if (it.last().address==mAddress){
                tempNumList.clear()
                it.forEach { bean ->
                    tempNumList.add(bean.temperatureNUm)
                }
                mViewModel.setTempNum(tempNumList, currentPosition)
            }
        })

        mViewModel.tempNumData.observe(this, Observer {
            if (it == "N/A") {
                tempNUm.setTextColor(Color.GRAY)
            } else {
                tempNUm.setTextColor(Color.RED)
            }
            tempNUm.text = it
        })

        mViewModel.profileData.observe(this, Observer {
            if (it.highTemperatureNum.isEmpty() && it.lowTemperatureNum.isEmpty() && !it.singleTemp) {
                tempHigh.isInvisible = true
                tempHighImg.isInvisible = true
                tempLow.isInvisible = true
                tempLowImg.isInvisible = true
                profileName.setText(R.string.text_no_profile)
            } else if (it.singleTemp) {
                tempHigh.text = LocalDataDao.INSTANCE.formatHighValueUnit(it)
                tempHigh.isInvisible = false
                tempHighImg.isInvisible = false
                tempLow.isInvisible = true
                tempLowImg.isInvisible = true
                profileName.text = it.name
            } else {
                tempHigh.text = LocalDataDao.INSTANCE.formatHighValueUnit(it)
                tempLow.text = LocalDataDao.INSTANCE.formatLowValueUnit(it)
                tempHigh.isInvisible = false
                tempHighImg.isInvisible = false
                tempLow.isInvisible = false
                tempLowImg.isInvisible = false
                profileName.text = it.name
            }
            imageTag.setImageResource(it.iconRes)

        })
        mViewModel.getProfile(currentPosition,mAddress)

        mViewModel.setTempNum(tempNumList, currentPosition)
        if (currentPosition != -1) {
            viewPage.setCurrentItem(currentPosition, true)
            (radioGroup.getChildAt(currentPosition) as RadioButton).isChecked=true
        }
    }

    private fun initListener() {
        backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }

        viewPage.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                if (!(radioGroup.getChildAt(position) as RadioButton).isChecked) {
                    radioGroup.check(position)
                }
                (radioGroup.getChildAt(position) as RadioButton).text = (position + 1).toString()
                for (i in 0 until 4) {
                    if (i != position) {
                        (radioGroup.getChildAt(i) as RadioButton).setText(R.string.text_null)
                    }
                }
                currentPosition = position
                mViewModel.getProfile(currentPosition,mAddress)
                mViewModel.setTempNum(tempNumList, currentPosition)
            }

            override fun onPageScrollStateChanged(state: Int) {

            }

        })
        page1.setOnClickListener(pageButtonClickListener)
        page2.setOnClickListener(pageButtonClickListener)
        page3.setOnClickListener(pageButtonClickListener)
        page4.setOnClickListener(pageButtonClickListener)

        viewShare.setOnClickListener {
            val uri = shareLayout.saveImage()
            uri?.let {
                val type = "image/*"

                startActivity(
                    ShareCompat
                        .IntentBuilder
                        .from(requireActivity())
                        .setType(type)
                        .setStream(Uri.parse(uri)).intent
                )
            }
        }

        viewHistory.setOnClickListener {
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(
                    R.anim.translate_into, R.anim.translate_out,
                    R.anim.translate_into_pop, R.anim.translate_out_exit
                )
                .add(
                    R.id.mainContent,
                    HistoryFragment.newInstance( currentPosition, mDeviceType, mAddress)
                )
                .addToBackStack("main")
                .commit()
        }
    }

    private val pageButtonClickListener = View.OnClickListener {
        var currentPosition = 0
        when (it.id) {
            R.id.page1 -> {
                currentPosition = 0
            }
            R.id.page2 -> {
                currentPosition = 1
            }
            R.id.page3 -> {
                currentPosition = 2
            }
            R.id.page4 -> {
                currentPosition = 3
            }
        }
        if (viewPage.currentItem != currentPosition) {
            viewPage.setCurrentItem(currentPosition, true)
        }
    }


}